<template>
  <div class="nft">
    <div class="nft-img" style="margin-bottom: 60px">
      <nut-image :src="nftAttrs.metadataImage" width="120" height="120" round />
      <div class="nft-name">{{ nftAttrs.goodsName }}</div>
      <div class="nft-desc">
        {{ nftAttrs.description }}
      </div>
    </div>

    <nut-cell title="合约地址">
      <template v-slot:link>
        <div>{{ nftAttrs.contract.contract }}</div>
      </template>
    </nut-cell>
    <nut-cell title="售价" v-if="state.showPrice">
      <template v-slot:link>
        <div>{{nftAttrs.price}} 元</div>
      </template>
    </nut-cell>
    <!-- <nut-cell title="系列">
      <template v-slot:link>
        <div>{{ nftAttrs.goodsName }}</div>
      </template>
    </nut-cell> -->
    <div style="text-align: center; margin-top: 20px; padding: 25px">
      <nut-button v-if="nftAttrs.obtainMethod == 2" color="#7232dd" size="large" @click="buyNftHandle">{{textRes.buyBtn}}</nut-button>
      <nut-button v-else color="#7232dd" size="large" @click="obtainNftHandle">{{textRes.opBtn}}</nut-button>
    </div>

    <nut-popup
      :style="{ padding: '14px 20px', width: '70%', height: '120px' }"
      round
      teleport="#app"
      v-model:visible="state.showObtain"
    >
      <div id="preloader_1">
        <span></span>
        <span></span>
        <span></span>
        <span></span>
        <span></span>
      </div>
    </nut-popup>

    <nut-popup
      :style="{ padding: '24px 14px 20px 20px', width: '70%', height: '120px'}"
      round
      teleport="#app"
      v-model:visible="state.showTeleport"
    >
      <nut-input v-model="nftAttrs.password" placeholder="请输入领取口令" />
      <div style="text-align: center; margin-top: 20px">
        <nut-button color="#7232dd" plain size="large" @click="getAnywebInfo"
          >确定</nut-button
        >
      </div>
    </nut-popup>
    <p style="text-align: center; margin-top: 100px; font-size: 14px; color: #999;">
      s11e-dao 提供技术支持
    </p>
  </div>
</template>

<script setup>
import { onMounted, reactive } from "vue";
import { Provider } from "@idealight-labs/anyweb-js-sdk";
import { getGoodsDetail, obtainNft, obtainNftPasswordCheck } from "@/api/nft";
import { Toast } from "@nutui/nutui";
import { getUrlParams } from "../utils/getUrlParams";
import { useRouter } from "vue-router";

const router = useRouter()

const provider = new Provider({
  // logger: console,
  appId: "ed6f4342-3a51-4b87-bd47-02ff13a04962",
});

onMounted(() => {
  getNftDetail();
});

provider.on("ready", () => {
  console.log("SDK 初始化完成 可以调用接口方法");
  // provider
  //   .request({
  //     method: "cfx_accounts",
  //     params: [
  //       {
  //         availableNetwork: [1, 1029],
  //         scopes: ["baseInfo", "identity"],
  //       },
  //     ],
  //   })
  //   .then((data) => {
  //     const { chainId, networkId, address, code } = data;
  //     console.log("DApp 获取到的授权结果", chainId, networkId, address, code);
  //   })
  //   .catch((e) => {
  //     console.error("调用失败", e);
  //   });
});

const state = reactive({
  showPrice: false,
  showTeleport: false,
  showObtain: false,
});

// nft属性
let nftAttrs = reactive({
  serialNo: null,
  password: null,
  tokenId: null,
  goodsName: null,
  description: null,
  obtainMethod: null, // 领取方式：1 免费领取/空投 2 购买  3 口令领取 4 一人一码口令领取
  contract: {
    contract: "",
  },
  price: 0,
  metadataImage: null,
});

let textRes = reactive({
  title: "领取NFT",
  opBtn: "领取NFT",
  buyBtn: "购买NFT",
});

// 领取Nft逻辑
const obtainNftHandle = async () => {

  // 判断nft类型是否需要口令
  if (nftAttrs.obtainMethod == 3 || nftAttrs.obtainMethod == 4) {
    state.showTeleport = true;
    return;
  }

  // 没有口令直接唤起钱包
  getAnywebInfo();  
};

// 购买Nft逻辑
const buyNftHandle = async () => {
  // 没有口令直接唤起钱包
  getAnywebInfo();
  // 根据钱包账户创建铸造订单
};

const getAnywebInfo = async () => {

  // 先检查口令是否正确
  if(nftAttrs.obtainMethod == 3 || nftAttrs.obtainMethod == 4){
    let obtainNftPasswordCheckParams = {
        serialNo: nftAttrs.serialNo,
        password: nftAttrs.password,
      };
      state.showObtain = true;
      const res = await obtainNftPasswordCheck({ ...obtainNftPasswordCheckParams })
      if (res.data.code != "000000") {
        state.showObtain = false;
        Toast.success(res.data.message);
        return
      }
      state.showTeleport = false;
  }

  const data = await provider.request({
    method: "cfx_accounts",
    params: [
      {
        availableNetwork: [1, 1029],
        scopes: ["baseInfo", "identity"],
      },
    ],
  });
  console.log(data)

  const { chainId, networkId, address, code } = data;
  sessionStorage.setItem("anywebCode",code);
  sessionStorage.setItem("toAddress",address[0]);
  console.log("DApp 获取到的授权结果", chainId, networkId, address, code);

  // 从路由中获取参数，请求后台数据
  let urlParts1 = (window.location.search || window.location.href).split("?");
  let urlParams1 = getUrlParams(urlParts1)

  // 判断是否需要购买如果需要购买跳转到购买页面
  if (nftAttrs.obtainMethod == 2) {
    console.log(router)
    state.showPrice = true;
    router.push("buyNft/?serialNo="+nftAttrs.serialNo)
    return;
  }

  let obtainNftParams = {
    code: code,
    serialNo: nftAttrs.serialNo,
    tokenId: nftAttrs.tokenId,
    toAddress: address[0],
    password: nftAttrs.password,
    chainEnv: urlParams1["chainEnv"],
  };
  state.showObtain = true;
  obtainNft({ ...obtainNftParams }).then((res) => {
    console.log(res);
    state.showObtain = false;
    if (res.data.code == "000000") {
      Toast.success("领取成功");
      router.push("obtainNftSuccess")
      nftAttrs.password = null
    } else {
      Toast.success(res.data.message);
    }
  });
  // 授权成功进行一个注册，然后在进行登录
};

const getNftDetail = async () => {
  // 从路由中获取参数，请求后台数据
  let urlParts = (window.location.search || window.location.href).split("?");
  let urlParams = getUrlParams(urlParts)

   nftAttrs.serialNo = urlParams["serialNo"]
  
  if (!nftAttrs.serialNo) {
    console.log("未获取到 serialNo，采用测试参数 1579754795437264896");
    return
  }
  getGoodsDetail({ serialNo: nftAttrs.serialNo }).then((res) => {
    console.log(res.data);
    nftAttrs.description = res.data.data.description;
    nftAttrs.contract.contract = res.data.data.contract?.contract;
    nftAttrs.goodsName = res.data.data.goodsName;
    nftAttrs.tokenId = res.data.data.tokenId;
    nftAttrs.metadataImage = res.data.data.preview;
    nftAttrs.obtainMethod = res.data.data?.obtainMethod
    nftAttrs.price = res.data.data?.price
    if (nftAttrs.obtainMethod == 2) {
      state.showPrice = true;
    }
  });
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.nft {
  padding-top: 30px;
}
.nft-title {
  text-align: center;
  font-size: 18px;
  letter-spacing: 2px;
  color: #666;
  padding: 8px;
  margin: 8px auto 60px auto;
  border-bottom: 1px solid #ddd;
}
.nft-img {
}

.nft-name {
  text-align: center;
  font-size: 15px;
  letter-spacing: 1px;
  color: #333;
  padding: 30px 15px 5px 15px;
}

.nft-desc {
  text-align: center;
  font-size: 12px;
  line-height: 160%;
  color: #888;
  padding: 8px 80px;
}

.nft-img view {
  margin: 0 auto !important;
}

.nut-cell__title {
  flex-direction: row !important;
}

#preloader_1 {
  position: relative;
  left: 100px;
  top: 60px;
  width: 100px;
}
#preloader_1 span {
  display: block;
  bottom: 0px;
  width: 9px;
  height: 5px;
  background: #fe7c24;
  position: absolute;
  animation: preloader_1 1.5s infinite ease-in-out;
}
#preloader_1 span:nth-child(2) {
  left: 11px;
  animation-delay: 0.2s;
}
#preloader_1 span:nth-child(3) {
  left: 22px;
  animation-delay: 0.4s;
}
#preloader_1 span:nth-child(4) {
  left: 33px;
  animation-delay: 0.6s;
}
#preloader_1 span:nth-child(5) {
  left: 44px;
  animation-delay: 0.8s;
}
@keyframes preloader_1 {
  0% {
    height: 5px;
    transform: translateY(0px);
    background: #fe7c24;
  }
  25% {
    height: 30px;
    transform: translateY(15px);
    background: #fe7c24;
  }
  50% {
    height: 5px;
    transform: translateY(0px);
    background: #fe7c24;
  }
  100% {
    height: 5px;
    transform: translateY(0px);
    background: #fe7c24;
  }
}

.nut-cell > div {
  width: 200px !important;
  /*1.强制不换行*/
  white-space: nowrap !important;
  /*2.溢出隐藏*/
  overflow: hidden !important;
  /*3.超出部分用省略号表示*/
  text-overflow: ellipsis !important;
  text-align: right;
}

.popclass1{
  border-radius: 20px !important;
}
</style>


